// 消息服务
import { apiService } from './api'
import type { 
  SendMessageRequest, 
  MessageResponse, 
  GetMessagesRequest, 
  PaginatedResponse,
  MarkMessageReadRequest,
  ConversationListResponse,
  MessageType,
  MessageContent
} from '@/types'

export class MessageService {
  /**
   * 发送文本消息
   */
  async sendTextMessage(
    conversationId: string, 
    text: string, 
    replyToMessageId?: string
  ): Promise<MessageResponse> {
    const request: SendMessageRequest = {
      conversationId,
      messageType: 'TEXT',
      content: { text },
      replyToMessageId,
      clientMessageId: this.generateClientMessageId()
    }
    
    return apiService.sendMessage(request)
  }

  /**
   * 发送图片消息
   */
  async sendImageMessage(
    conversationId: string, 
    imageUrl: string, 
    thumbnailUrl?: string
  ): Promise<MessageResponse> {
    const request: SendMessageRequest = {
      conversationId,
      messageType: 'IMAGE',
      content: { imageUrl, thumbnailUrl },
      clientMessageId: this.generateClientMessageId()
    }
    
    return apiService.sendMessage(request)
  }

  /**
   * 发送文件消息
   */
  async sendFileMessage(
    conversationId: string, 
    fileUrl: string, 
    fileName: string, 
    fileSize: number
  ): Promise<MessageResponse> {
    const request: SendMessageRequest = {
      conversationId,
      messageType: 'FILE',
      content: { fileUrl, fileName, fileSize },
      clientMessageId: this.generateClientMessageId()
    }
    
    return apiService.sendMessage(request)
  }

  /**
   * 发送语音消息
   */
  async sendVoiceMessage(
    conversationId: string, 
    fileUrl: string, 
    duration: number
  ): Promise<MessageResponse> {
    const request: SendMessageRequest = {
      conversationId,
      messageType: 'VOICE',
      content: { fileUrl, duration },
      clientMessageId: this.generateClientMessageId()
    }
    
    return apiService.sendMessage(request)
  }

  /**
   * 发送通用消息
   */
  async sendMessage(
    conversationId: string,
    messageType: MessageType,
    content: MessageContent,
    replyToMessageId?: string
  ): Promise<MessageResponse> {
    const request: SendMessageRequest = {
      conversationId,
      messageType,
      content,
      replyToMessageId,
      clientMessageId: this.generateClientMessageId()
    }
    
    return apiService.sendMessage(request)
  }

  /**
   * 获取会话消息列表（分页）
   */
  async getMessages(
    conversationId: string,
    page = 1,
    pageSize = 20,
    beforeMessageId?: string
  ): Promise<PaginatedResponse<MessageResponse>> {
    const request: GetMessagesRequest = {
      conversationId,
      page,
      pageSize,
      beforeMessageId
    }
    
    return apiService.getConversationMessages(request)
  }

  /**
   * 获取历史消息（向前加载）
   */
  async getHistoryMessages(
    conversationId: string,
    beforeMessageId: string,
    pageSize = 20
  ): Promise<PaginatedResponse<MessageResponse>> {
    const request: GetMessagesRequest = {
      conversationId,
      pageSize,
      beforeMessageId
    }
    
    return apiService.getConversationMessages(request)
  }

  /**
   * 获取新消息（向后加载）
   */
  async getNewMessages(
    conversationId: string,
    afterMessageId: string,
    pageSize = 50
  ): Promise<PaginatedResponse<MessageResponse>> {
    const request: GetMessagesRequest = {
      conversationId,
      pageSize,
      afterMessageId
    }
    
    return apiService.getConversationMessages(request)
  }

  /**
   * 标记单个消息为已读
   */
  async markMessageAsRead(messageId: string, conversationId: string): Promise<void> {
    const request: MarkMessageReadRequest = {
      messageId,
      conversationId
    }
    
    return apiService.markMessageAsRead(request)
  }

  /**
   * 批量标记消息为已读
   */
  async markMessagesAsRead(conversationId: string, messageIds: string[]): Promise<void> {
    return apiService.markMessagesAsRead(conversationId, messageIds)
  }

  /**
   * 标记会话所有消息为已读
   */
  async markConversationAsRead(conversationId: string): Promise<void> {
    // 获取未读消息ID列表，然后批量标记为已读
    try {
      const messages = await this.getMessages(conversationId, 1, 100)
      const unreadMessageIds = messages.items
        .filter(msg => !msg.isRead)
        .map(msg => msg.messageId)
      
      if (unreadMessageIds.length > 0) {
        await this.markMessagesAsRead(conversationId, unreadMessageIds)
      }
    } catch (error) {
      console.error('Failed to mark conversation as read:', error)
      throw error
    }
  }

  /**
   * 获取会话列表
   */
  async getConversations(): Promise<ConversationListResponse> {
    return apiService.getConversations()
  }

  /**
   * 生成客户端消息ID
   */
  private generateClientMessageId(): string {
    return `client_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  }

  /**
   * 重试发送失败的消息
   */
  async retryMessage(originalRequest: SendMessageRequest): Promise<MessageResponse> {
    // 生成新的客户端消息ID
    const request = {
      ...originalRequest,
      clientMessageId: this.generateClientMessageId()
    }
    
    return apiService.sendMessage(request)
  }
}

export const messageService = new MessageService()